import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart' as GET;
import 'package:path_provider/path_provider.dart';
import 'package:sptapp/api/interface/user_api.dart';
import 'package:sptapp/api/request/response_data.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/moudle/common_info.dart';
import 'package:sptapp/widget/common_widget.dart';

import '../../api/interface/login_api.dart';
import '../../moudle/media/media_picker.dart';
import '../../widget/cache_image.dart';
import 'package:dio/dio.dart';

class MinChangeAvatar extends StatefulWidget {
  const MinChangeAvatar({super.key});

  @override
  State<MinChangeAvatar> createState() => _MinChangeAvatarState();
}

class _MinChangeAvatarState extends State<MinChangeAvatar> {

  String imgUrl = 'assets/home/home_person.png';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, 'Avatar'),
      body: Container(
        child: Column(
          children: [
            SizedBox(height: 260.h,),
            Container(
              decoration: BoxDecoration(
                color: Color.fromRGBO(255, 255, 255, 0.1)
              ),
              child: CacheImage(
                image: baseUserInfo['avatar']??'assets/home/home_person.png',
                width: 650.w,
                height: 650.w,
                fit: BoxFit.fitWidth,
              ),
            ),
            SizedBox(height: 180.h,),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 40.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: ()async{
                      List<MediaAssetDataEntity> list = await MyMediaPicker.imgPick(isCamera: true);
                      if(list.isNotEmpty){
                        uploadImg(list[0].uri);
                      }
                      },
                    child: Container(
                      child: Column(
                        children: [
                          Image.asset('assets/common/min_camera.png',width: 64.w,),
                          Text('Camera'.tr,style: TextStyle(
                              color: Colors.white,
                              fontSize: 28.sp
                          )),
                        ],
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: ()async{
                      List<MediaAssetDataEntity> list = await MyMediaPicker.imgPick(isCamera: false);
                      if(list.isNotEmpty){
                       uploadImg(list[0].uri);
                      }
                    },
                    child: Container(
                      child: Column(
                        children: [
                          Image.asset('assets/home/scan_photo.png',width: 64.w,),
                          Text('Library'.tr,style: TextStyle(
                              color: Colors.white,
                              fontSize: 28.sp
                          ),),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  uploadImg(String uri)async{
    print('uri ====   $uri');

    String path = uri;
    try{
      String targetPath = '${(await getTemporaryDirectory()).path}/temp.jpeg';
      var result =  await FlutterImageCompress.compressAndGetFile(
          uri, targetPath,
          quality: 80,
          minWidth: 500,
          minHeight: 500
      );
      path = result!.path;
    }catch(e){
      print('error ====  $e');
      path = uri;
    }

    print('tupiandizhi ====  $path');
    showLoading();
    FormData formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(path, filename: 'avatar.png'),
    });
    ResponseData res = await UserAPI.commonUpload(formData);
    hideLoading();
    if(res.code == 200){
      showLoading();
      res = await LoginAPI.userEdit({
        'avatar': res.data['url']
      });
      hideLoading();
      if(res.code == 200){
        setState(() {
          baseUserInfo['avatar'] = uri;
          avatarPath = uri;
          showToast('Success');
        });
      }
    }
  }
}
